const CFG = require('../config');
const EC = require('../comm/err-code');
const FUN = require('../comm/func');
const helper = require('../comm/api-helper');
const rCache = require('../model/redis_cache');
const tbUserId = require('../model/tb_user_id');
const express = require('express');
const api = express();

// 提供给boom，传递用户信息，缓存到redis中
api.post('/set', (req,resp)=>{
  let param = req.body;
  let res = {code:EC.SUCESS, msg:EC.SUCESS_MSG};

  // 参数校验
  if(!isVaild(param.token)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':token'});
  if(!isNum(param.uid) || parseInt(param.uid) <= 0) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':uid'});
  if(!isVaild(param.user)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':user'});
  if(!isNum(param.level)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':level'});
  if(!isVaild(param.auth)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG+':auth'});
  // todo 此处应该校验token的合法性 num-num*7

  let cacheInfo = {token:param.token, uid:param.uid, user:param.user, level:param.level, auth:param.auth};
  rCache.set(rCache.N_UserAuth, param.token, cacheInfo, CFG.USER_TOKEN_EXPIRE).then(res=>{
    console.log(" - token", param.token, "for", param.user, "["+param.uid+"]");
    let dbInfo = {name:param.user, level:param.level, auth:param.auth, token:param.token};
    tbUserId.recordUser(param.uid, dbInfo); // 记录到数据库
  })

  resp.json(res);
})

// 提供给boom，退出登录时清除信息
api.post('/clear', (req,resp)=>{
  let param = req.body;
  let res = {code:EC.SUCESS, msg:EC.SUCESS_MSG};

  if(param.token){
    rCache.del(rCache.N_UserAuth, param.token).then(res=>{
      console.log(" - token", param.token, "be clear");
    })
  }
  resp.json(res);
})

// 提供给前台，用于登录mqtt服务器
api.post('/mq-info', async(req,resp)=>{
  let param = req.body;
  let res = {code:EC.FAILD, msg:EC.FAILD_MSG};

  // 合法性校验
  let uInfo = await helper.CheckToken(param.token);
  if(!uInfo.uid) return resp.json({code:EC.AUTH_ERR, msg:EC.AUTH_ERR_MSG});

  // 参数校验
  if(!isVaild(param.path)) return resp.json({code:EC.PARAM_ERROR, msg:EC.PARAM_ERROR_MSG});

  let mqInfo = {};
  if (param.path == 'dev/ctrl') {
    mqInfo.user = 'login';
    mqInfo.pw = CFG.GetDevAuthCode(uInfo.uid).toString();
    mqInfo.id = 'login.'+uInfo.uid+'.'+FUN.rand(123456,999999);
  } else if (param.path == 'panel/index') {
    mqInfo.user = 'login';
    mqInfo.pw = CFG.GetDevAuthCode(uInfo.uid).toString();
    mqInfo.id = 'login.'+uInfo.uid+'.'+FUN.rand(123456,999999);
  }

  res.code = EC.SUCESS;
  res.msg = EC.SUCESS_MSG;
  res.mq = mqInfo;
  resp.json(res);
})


module.exports = api;